package com.zrf.gulimall.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrf.gulimall.commnon.core.enums.AttrTypeEnum;
import com.zrf.gulimall.common.database.utils.PageUtils;
import com.zrf.gulimall.common.database.utils.Query;
import com.zrf.gulimall.product.dao.AttrDao;
import com.zrf.gulimall.product.entity.*;
import com.zrf.gulimall.product.service.AttrAttrGroupRelationService;
import com.zrf.gulimall.product.service.AttrGroupService;
import com.zrf.gulimall.product.service.AttrService;
import com.zrf.gulimall.product.service.CategoryService;
import com.zrf.gulimall.product.vo.AttrRespVo;
import com.zrf.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

	@Resource
	private AttrAttrGroupRelationService attrAttrgroupRelationService;
	@Resource
	private AttrGroupService attrGroupService;
	@Resource
	private CategoryService categoryService;

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void saveAttr(AttrVo attr) {
		AttrEntity attrEntity = new AttrEntity();
		BeanUtils.copyProperties(attr, attrEntity);
		// 保存基本数据
		baseMapper.insert(attrEntity);
		// 保存级联关系
		if (attrEntity.getAttrType().equals(AttrTypeEnum.ATTR_TYPE_BASE.getCode()) && Objects.nonNull(attr.getAttrGroupId())) {
			AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
			relationEntity.setAttrId(attrEntity.getAttrId());
			relationEntity.setAttrGroupId(attr.getAttrGroupId());
			attrAttrgroupRelationService.save(relationEntity);
		}
	}

	@Override
	public PageUtils queryPage(Map<String, Object> params, Long catelogId, String attrType) {
		Integer type = "base".equalsIgnoreCase(attrType) ? AttrTypeEnum.ATTR_TYPE_BASE.getCode() : AttrTypeEnum.ATTR_TYPE_SALE.getCode();
		String key = (String) params.get("key");
		IPage<AttrEntity> page = this.lambdaQuery()
				.eq(!catelogId.equals(0L), AttrEntity::getCatelogId, catelogId)
				.eq(StrUtil.isNotEmpty(attrType), AttrEntity::getAttrType, type)
				.and(
						StrUtil.isNotEmpty(key),
						wrapper -> wrapper.eq(AttrEntity::getAttrId, key)
								.or().like(AttrEntity::getAttrName, key)
				)
				.page(new Query<AttrEntity>().getPage(params));
		PageUtils pageUtils = new PageUtils(page);
		List<AttrEntity> records = page.getRecords();
		// 查询关联值
		if (CollUtil.isNotEmpty(records)) {
			// 查询关联的目录，并按id为键转为map
			List<Long> catalogIdList = records.stream().map(AttrEntity::getCatelogId).distinct().collect(Collectors.toList());
			List<CategoryEntity> categoryList = categoryService.listByIds(catalogIdList);
			Map<Long, CategoryEntity> categoryMap = categoryList.stream().collect(Collectors.toMap(CategoryEntity::getCatId, Function.identity()));
			// 查询关联的属性分组
			List<Long> attrIdList = records.stream().map(AttrEntity::getAttrId).collect(Collectors.toList());
			// 查询关联对象集
			Map<Long, String> attrIdGroupIdMap = MapUtil.newHashMap();
			List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationService.queryByAttrIds(attrIdList);
			if (CollUtil.isNotEmpty(relationEntities)) {
				// 根据属性组id查询属性组对象集，并以属性组id为key，属性组名为value，转为map
				List<AttrGroupEntity> attrGroupEntities = attrGroupService.listByIds(relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrGroupId).distinct().collect(Collectors.toList()));
				Map<Long, String> attrGroupMap = attrGroupEntities.stream().collect(Collectors.toMap(AttrGroupEntity::getAttrGroupId, AttrGroupEntity::getAttrGroupName));
				// 属性id-所属属性组名称map
				attrIdGroupIdMap.putAll(relationEntities.stream().collect(Collectors.toMap(AttrAttrgroupRelationEntity::getAttrId, item -> attrGroupMap.get(item.getAttrGroupId()))));
			}
			// 转换为vo返回
			List<AttrRespVo> list = records.stream().map(item -> {
				AttrRespVo attrRespVo = new AttrRespVo();
				BeanUtils.copyProperties(item, attrRespVo);
				// 设置分类名称
				CategoryEntity categoryEntity = categoryMap.get(item.getCatelogId());
				if (categoryEntity != null) {
					attrRespVo.setCatelogName(categoryEntity.getName());
				}
				// 设置分组名称
				String attrGroupName = attrIdGroupIdMap.get(item.getAttrId());
				if (Objects.nonNull(attrGroupName)) {
					attrRespVo.setGroupName(attrGroupName);
				}
				return attrRespVo;
			}).collect(Collectors.toList());
			pageUtils.setList(list);
		}
		return pageUtils;
	}

	@Override
	public List<AttrEntity> queryByGroupId(Long attrGroupId) {
		List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationService.queryByAttrGroupId(attrGroupId);
		List<Long> attrIdList = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
		if (CollUtil.isEmpty(attrIdList)) {
			return null;
		}
		return this.listByIds(attrIdList);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void update(AttrVo attrVo) {
		AttrEntity attrEntity = new AttrEntity();
		BeanUtils.copyProperties(attrVo, attrEntity);
		this.updateById(attrEntity);
		// 如果是基础属性，更新或修改级联表
		if (attrVo.getAttrType().equals(AttrTypeEnum.ATTR_TYPE_BASE.getCode())) {
			AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
			attrAttrgroupRelationEntity.setAttrId(attrVo.getAttrId());
			attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
			attrAttrgroupRelationService.saveOrUpdate(attrAttrgroupRelationEntity,
					Wrappers.<AttrAttrgroupRelationEntity>lambdaUpdate()
							.eq(AttrAttrgroupRelationEntity::getAttrId, attrVo.getAttrId()));
		}
	}

	@Override
	public PageUtils queryNoRelationByGroupId(Map<String, Object> params, Long attrGroupId) {
		String key = (String) params.get("key");
		AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrGroupId);
		// 查询当前分类下的其他属性分组
		List<AttrGroupEntity> attrGroupEntities = attrGroupService.queryByCatalogId(attrGroupEntity.getCatelogId());
		List<Long> groupIdList = attrGroupEntities.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());
		// 查询这些属性分组关联的属性id，并剔除
		List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationService.queryByAttrGroupIds(groupIdList);
		List<Long> relationAttrIdList = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
		IPage<AttrEntity> page = this.lambdaQuery()
				.eq(AttrEntity::getAttrType, AttrTypeEnum.ATTR_TYPE_BASE.getCode())
				.eq(AttrEntity::getCatelogId, attrGroupEntity.getCatelogId())
				.notIn(CollUtil.isNotEmpty(relationAttrIdList), AttrEntity::getAttrId, relationAttrIdList)
				.and(StrUtil.isNotEmpty(key), wrapper -> wrapper.eq(AttrEntity::getAttrId, key).or().like(AttrEntity::getAttrName, key))
				.page(new Query<AttrEntity>().getPage(params));
		return new PageUtils(page);
	}

	@Override
	public AttrVo queryRelationInfoById(Long attrId) {
		AttrEntity attr = this.getById(attrId);
		AttrVo attrVo = new AttrVo();
		BeanUtil.copyProperties(attr, attrVo);
		// 设置分类信息
		Long[] catelogPath = categoryService.findCatelogPath(attr.getCatelogId());
		attrVo.setCatelogPath(catelogPath);
		// 设置分组信息
		if (attr.getAttrType().equals(AttrTypeEnum.ATTR_TYPE_BASE.getCode())) {
			AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.queryByAttrId(attrId);
			if (Objects.nonNull(relationEntity)) {
				attrVo.setAttrGroupId(relationEntity.getAttrGroupId());
			}
		}
		return attrVo;
	}

}